<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="">
        <BasicTree
          :treeData="treeData"
          :fieldNames="{ title: 'name', key: 'key' }"
          :checkedKeys="checkedKeys"
          checkable
          checkStrictly
          toolbar
          title="菜单分配"
          @check="onCheck"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import {
    queryRolePermission,
    saveRolePermission,
    saveOrUpdateRole,
  } from '/@/api/system/role/role.api';
  import { getMenuList } from '/@/api/system/menu/menu.api';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref([]);
      const checkedKeys = ref<String[]>([]);
      const rolePermission = ref([]);
      const roleId = ref('');
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          treeData.value = (await getMenuList()) as any as TreeItem[];
        }

        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          //如果是更新则获取角色对应的菜单权限
          rolePermission.value = await queryRolePermission({ roleId: data.record.id });
          checkedKeys.value = rolePermission.value;
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      function onCheck(o) {
        checkedKeys.value = o;
      }
      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          await saveOrUpdateRole(values, unref(isUpdate)).then((res) => {
            if (!unref(isUpdate)) {
              roleId.value = res.id;
            } else {
              roleId.value = values.id;
            }
          });
          await saveRolePermission({
            roleId: roleId.value,
            lastpermissionIds: unref(rolePermission) ? unref(rolePermission).join(',') : '',
            permissionIds: unref(checkedKeys).checked ? unref(checkedKeys).checked.join(',') : '',
          });
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        checkedKeys,
        onCheck,
      };
    },
  });
</script>
